//
//  Database.m
//  FMDBTest
//
//  Created by  on 12-3-27.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "Database.h"
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
#import "UserEntity.h"
//#import "JSON.h"
//#import "NSDictionary+safeObjectForKey.h"
//#import "ActivityView.h"


@implementation Database

static Database *sqlManager = nil;

+ (Database*)sharedManager
{
    @synchronized(self) {
        if (sqlManager == nil) {
            sqlManager = [[Database alloc] init]; // assignment not done here
        }
    }
    return sqlManager;
}

+ (id)allocWithZone:(NSZone *)zone
{
    @synchronized(self) {
        if (sqlManager == nil) {
            sqlManager = [super allocWithZone:zone];
            return sqlManager;  // assignment and return on first allocation
        }
    }
    return nil; //on subsequent allocation attempts return nil
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)init
{
    self = [super init];
    if (self) {
        BOOL success;
        NSFileManager *fm = [NSFileManager defaultManager];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
        NSString *cachesDir = [paths objectAtIndex:0];
        NSString *DBPath = [cachesDir stringByAppendingPathComponent:DB_NAME];
        success = [fm fileExistsAtPath:DBPath];
        if (!success) {
//            success = [fm createFileAtPath:DBPath contents:nil attributes:nil];
            success = [fm copyItemAtPath:[[NSBundle mainBundle] pathForResource:@"study" ofType:@"db"] toPath:DBPath error:nil];
            if (!success) {
                return nil;
            }
            success = YES;
        }
        if (success) {
            db = [FMDatabase databaseWithPath:DBPath];
            if ([db open]) {
                [db setShouldCacheStatements:YES];
                NSLog(@"Open success db !");
            }else {
                NSLog(@"Failed to open db!");
                return nil;
            }
        }
        [db close];
    }
        
    return self;
}

- (NSArray *)querySecondCitys:(int)area_id
{
    [db open];
    NSString *sql = @"SELECT id,areacode,areaname,parentid FROM t_area where parentid = ?";
    if (area_id == 1 || area_id == 795 || area_id == 18 || area_id == 2250) {
        sql = @"SELECT id,areacode,areaname,parentid FROM t_area where id = ?";
    }
    FMResultSet *rs = [db executeQuery:sql,[NSNumber numberWithInt:area_id]];
    NSMutableArray *ary = [NSMutableArray array];
    while ([rs next]) {
        NSDictionary *dic = [rs resultDictionary];
        [ary addObject:dic];
    }
    [rs close];
    [db close];
    return ary;
}

- (NSArray *)queryCitys:(int)area_id;
{
    [db open];
    NSString *sql = @"SELECT id,areacode,areaname,parentid FROM t_area where arealevel = ?";
    FMResultSet *rs = [db executeQuery:sql,[NSNumber numberWithInt:area_id]];
    NSMutableArray *ary = [NSMutableArray array];
    while ([rs next]) {
        NSDictionary *dic = [rs resultDictionary];
        [ary addObject:dic];
    }
    [rs close];
    [db close];
    return ary;
}

- (NSString *)queryCityCode:(NSString *)cityName
{
    NSString *name = @"";
    [db open];
    NSString *sql = [NSString stringWithFormat:@"SELECT areacode FROM t_area where areaname LIKE '%@%%'",cityName];
    FMResultSet *rs = [db executeQuery:sql];
    NSMutableArray *ary = [NSMutableArray array];
    while ([rs next]) {
        NSDictionary *dic = [rs resultDictionary];
        [ary addObject:dic[@"areacode"]];
    }
    [rs close];
    [db close];
    if (ary.count > 0) {
        name = ary.firstObject;
    }
    return name;
}
- (void)upateFirstChat:(NSString *)firstchat withRemark:(NSString *)area_id
{
    [db open];
    NSString *sql = @"UPDATE t_area SET firstchat = ? WHERE areacode = ?";
    BOOL isSuccuss = [db executeUpdate:sql,firstchat,area_id];
    [db close];
    
}
- (BOOL)noData:(NSString *)consultationid
{
    int count = 0;
    NSString *sql = @"SELECT COUNT(*) re FROM t_mhsdmsg_master WHERE consultationid = ? and userid = ? ";
    FMResultSet *rs = [db executeQuery:sql,consultationid];
    
    while ([rs next]) {
        NSDictionary *dic = [rs resultDictionary];
        count = [[dic objectForKey:@"re"] intValue];
    }
    return count == 0;
}

- (int)getMsgSum:(NSString *)consultationId
{
    int sum = 0;
    
    NSString *sql = @"SELECT msgnums FROM t_mhsdmsg_master WHERE consultationid = ? ";
    FMResultSet *rs = [db executeQuery:sql,consultationId];
    while ([rs next]) {
        NSDictionary *dic = [rs resultDictionary];
        sum = [[dic objectForKey:@"msgnums"] intValue];
    }
    return sum;
}

- (int)queryMsgSum:(NSString *)consultationId
{
    int sum = 0;
    [db open];
    NSString *sql = @"SELECT msgnums FROM t_mhsdmsg_master WHERE consultationid = ? ";
    FMResultSet *rs = [db executeQuery:sql,consultationId];
    while ([rs next]) {
        NSDictionary *dic = [rs resultDictionary];
        sum = [[dic objectForKey:@"msgnums"] intValue];
    }
    [db close];
    return sum;
}

- (BOOL)saveAreaData:(NSDictionary *)dic
{
    [db open];
    BOOL success = NO;
    NSString *sql = @"INSERT INTO t_area (id,areacode,areaname,parentid,areanumber,arealevel) values(?,?,?,?,?,?)";
    success = [db executeUpdate:sql,
               dic[@"id"],
               dic[@"areacode"],
               dic[@"areaname"],
               dic[@"parentid"],
               dic[@"areanumber"],
               dic[@"arealevel"]];
    [db close];
    return success;
}

- (BOOL)saveMaster:(NSDictionary *)dic
{
    [db open];
    BOOL success = NO;
    [db close];
    return success;
}


- (NSArray *)queryMsgData:(NSString *)sessionID
{
    [db open];
    NSString *sql = @"SELECT * FROM t_mhsmsg where sessionid = ?";
    FMResultSet *rs = [db executeQuery:sql,sessionID];
    NSMutableArray *ary = [NSMutableArray array];
    while ([rs next]) {
        NSDictionary *dic = [rs resultDictionary];
        [ary addObject:dic];
    }
    [rs close];
    [db close];
    return ary;
}


@end
